<template>
  <div class="test">
    <ul class="test-tit clear">
      <li class="test-tit-left">{{ timeNum | secondsFormat }}</li>
      <li class="test-tit-mid">
        <div class="test-tit-mid-box">
          <span class="test-tit-mid-word"
            >{{ currentIndex + 1 }}/{{ question.length }}</span
          >
          <van-progress
            :percentage="((currentIndex + 1) / question.length) * 100"
            :show-pivot="false"
            stroke-width="8"
            style="width:200px"
          />
        </div>
      </li>
      <li class="test-tit-right" @click="handleAnswerCard"></li>
    </ul>
    <div class="test-bg">
      <div class="test-question" id="renderQuestion">
        <div class="test-question-tit clear">
          <span v-html="question[currentIndex].title"></span>
        </div>
        <ul class="test-question-answer">
          <li
            :class="fifterAnswer(item.answerId) ? 'test-hasSelect' : ''"
            v-for="(item, index) in question[currentIndex].answer"
            @click="selectAnswer(item)"
            :key="'answer' + item.answerId"
          >
            <div
              class="test_question_answer_left"
              v-html="treABCD[index]"
            ></div>
            <div class="test_question_answer_right" v-html="item.answer"></div>
          </li>
        </ul>
      </div>
    </div>
    <div class="test-next-btn">
      <van-button
        @click="nextQuestion"
        size="large"
        :disabled="
          !(answerList[currentIndex] && answerList[currentIndex].length > 0)
        "
        round
        block
        type="info"
        >{{
          this.currentIndex == question.length - 1
            ? "完 成 获 取 报 告"
            : "下 一 题"
        }}</van-button
      >
    </div>

    <van-action-sheet v-model="answerCardVisible" title="答题卡">
      <div class="test-answerCard-box">
        <ul class="test-chapterList clear">
          <li
            v-for="(item, index) in info.subInfo.chapterList"
            :key="'sub' + index"
          >
            {{ item }}
          </li>
        </ul>
        <ul class="test-answerCardList clear">
          <li
            v-for="(item, index) in question"
            :class="[
              (index + 1) % 5 === 0 ? '' : 'ts-mr73',
              answerList[index] && answerList[index].length > 0
                ? 'ts-hasAnswer'
                : ''
            ]"
            @click="goQuestion(index)"
            :key="'qs' + index"
          >
            {{ index + 1 }}
          </li>
        </ul>
      </div>
    </van-action-sheet>
  </div>
</template>
<style scoped></style>
<script>
import { evaluationCheck, verificationCode, getWechat } from "@/server/api.js";
import "katex/dist/katex.js";
import "katex/dist/katex.min.css";
import renderMathInElement from "katex/dist/contrib/auto-render.js";
import { mapGetters } from "vuex";
import { GetUrlParame } from "@/utils/utils";
export default {
  name: "test",
  components: {},
  data() {
    return {
      currentIndex: 0,  // 题目的下标  0开始
      answerList: [],  // 答题卡 - 已做/未做
      selectAnswerId: "",
      timeNum: 0,   // 做题总时间
      userId: "",
      startTime: 0,  // 每道题的开始时间 -- 计算每道题的使用时间
      dig_form: {
        name: "",
        phone: "",
        code: ""
      },
      answerCardVisible: false,  // 题目导航栏是否显示
      buttonBtn: false,
      time2: "",
      buttonName: "获取验证码",
      times: "",  // 时间定时器
      digBtn: false,
      treABCD: {    // 答案的选择项
        0: "A",
        1: "B",
        2: "C",
        3: "D",
        4: "E",
        5: "F",
        6: "G",
        7: "H",
        8: "G"
      },
      SelectAnswerlist: "",
      /* 
       --- 题目答案 ---
       cur_param = {
        usetime: 做题总时长
        currentIndex: {
          questionId: this.question[this.currentIndex].questionId, -- 题目id
          useTime: useTime, -- 做题时长
          isTrue: this.checkAnswer(), -- 是否已做
          answer: this.makeAnswer()  -- 答案
        }
       }
      */
      cur_param: {
        list: []
      }
    };
  },
  computed: {
    ...mapGetters(["question", "param", "info"])
  },
  updated() {},
  created() {
    if (!this.info.id) {
      this.$router.push({
        path: "/home"
      });
      return;
    }
    this.countTime();
    this.$nextTick(() => {
      this.renderDom();
    });
  },
  mounted() {},
  filters: {
    secondsFormat: function(s) {
      var day = Math.floor(s / (24 * 3600)); // Math.floor()向下取整
      var hour = Math.floor((s - day * 24 * 3600) / 3600);
      var minute = Math.floor((s - day * 24 * 3600 - hour * 3600) / 60);
      var second = s - day * 24 * 3600 - hour * 3600 - minute * 60;
      if (second < 10) {
        second = "0" + second;
      }
      if (minute < 10) {
        minute = "0" + minute;
      }
      if (hour < 10) {
        hour = "0" + hour;
      }
      // return hour + ":" + minute + ":" + second + "";
      return minute + ":" + second + "";
    }
  },
  watch: {
    currentIndex(nv, ov) {
      this.$nextTick(() => {
        this.renderDom();
      });
    }
  },
  methods: {
    goQuestion(index) {
      if (this.answerList[index] && this.answerList[index].length > 0) {
        console.log(index);
        this.currentIndex = index;
        this.answerCardVisible = false;
      } else {
        return;
      }
    },
    handleAnswerCard() {
      this.answerCardVisible = true;
    },
    getCode() {
      if (!this.dig_form.phone) {
        Toast({
          message: "请填写您的手机号码",
          position: "middle",
          duration: 2000
        });

        return;
      }
      if (!this.isPoneAvailable(this.dig_form.phone)) {
        Toast({
          message: "您的手机号码有误，请重新填写！",
          position: "middle",
          duration: 2000
        });
        return;
      }
      this.buttonBtn = true;

      let _param = {
        openId: this.param.wechatId,
        phone: this.dig_form.phone
      };

      verificationCode(_param).then(res => {
        if (res.code == 200) {
          this.timeComputer();
          Toast({
            message: "发送成功，请注意查收",
            position: "middle",
            duration: 2000
          });
        } else {
          this.buttonBtn = false;
          Toast({
            message: "发送失败，请重试",
            position: "middle",
            duration: 2000
          });
        }
      });
    },

    timeComputer() {
      let time = 60;
      let that = this;
      this.buttonName = time;
      this.time2 = setInterval(function() {
        time--;
        if (time < 0) {
          clearInterval(that.time2);
          that.buttonName = "获取验证码";
          that.buttonBtn = false;
          return;
        }
        that.buttonName = time;
      }, 1000);
    },
    selectAnswer(data) {
      this.answerList[this.currentIndex] = [];
      this.answerList[this.currentIndex].push(data.answerId);
      this.$forceUpdate();
    },
    fifterAnswer(id) {
      let selectAnswer = this.answerList[this.currentIndex];
      if (!selectAnswer || (selectAnswer && selectAnswer.length == 0)) {
        return false;
      }
      let innerIndex = selectAnswer.indexOf(id);
      return innerIndex > -1;
    },
    renderDom() {
      renderMathInElement(document.getElementById("renderQuestion"), {
        delimiters: [
          {
            left: "$$",
            right: "$$",
            display: true
          },
          {
            left: "\\[",
            right: "\\]",
            display: true
          },
          {
            left: "$",
            right: "$",
            display: false
          },
          {
            left: "\\(",
            right: "\\)",
            display: false
          }
        ]
      });
    },

    countTime() {
      let that = this;
      this.times = setTimeout(function() {
        that.timeNum += 1;
        that.countTime();
      }, 1000);
    },

    isPoneAvailable(num) {
      var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
      if (!myreg.test(String(num))) {
        return false;
      } else {
        return true;
      }
    },
    isUserName(name) {
      var myreg1 = /^[a-zA-Z ]{1,20}$/;
      var myreg2 = /^[\u4e00-\u9fa5]{1,10}$/;
      if (myreg1.test(String(name)) || myreg2.test(String(name))) {
        return true;
      } else {
        return false;
      }
    },

    saveInfo() {
      if (!this.dig_form.name) {
        Toast({
          message: "请填写你的姓名",
          position: "middle",
          duration: 2000
        });
        return;
      }
      if (!this.isUserName(this.dig_form.name)) {
        Toast({
          message: "请填写正确的姓名！",
          position: "middle",
          duration: 2000
        });
        return;
      }
      if (!this.dig_form.phone) {
        Toast({
          message: "请填写您的手机号码",
          position: "middle",
          duration: 2000
        });

        return;
      }
      if (!this.isPoneAvailable(this.dig_form.phone)) {
        Toast({
          message: "您的手机号码有误，请重新填写！",
          position: "middle",
          duration: 2000
        });
        return;
      }
      this.commitInfo(this.dig_form.code);
    },
    commitInfo() {
      this.cur_param.useTime = this.timeNum;
      let new_param = Object.assign({}, this.param, this.cur_param);
      // 将答案发送给后台
      evaluationCheck(new_param).then(res => {
        if (res.code == 200) {
          /* 后台生成报告 */
          /*
          this.info.paperId = res.data;
          this.info.useTime = this.timeNum;
          this.$store.dispatch("setInfo", this.info);
          this.$router.push({
            path: "/waitLoading"
          });
          */
         this.$router.push({
            path: "/commitpage"
          });
        } else {
          this.$toast({
            message: res.message,
            position: "middle",
            duration: 2000
          });
        }
      });
    },
    checkAnswer() {
      let isTrue = 0;
      let id = this.answerList[this.currentIndex][0];
      this.question[this.currentIndex].answer.map(item => {
        if (item.answerId == id) {
          isTrue = item.isTrue;
        }
      });
      return isTrue;
    },
    makeAnswer() {
      let selectAnswer = this.answerList[this.currentIndex];
      let questionAnswer = this.question[this.currentIndex].answer;
      let returnArr = [];
      questionAnswer.map(item => {
        if (selectAnswer[0] == item.answerId) {
          returnArr.push(item);
        }
      });
      return returnArr;
    },
    nextQuestion() {
      let useTime = this.timeNum - this.startTime;
      this.startTime = this.timeNum;
      // let answerList = this.answerList[this.currentIndex]

      let question = {
        questionId: this.question[this.currentIndex].questionId,
        useTime: useTime,
        isTrue: this.checkAnswer(),
        answer: this.makeAnswer()
      };
      this.cur_param.list[this.currentIndex] = question;
      if (this.currentIndex < this.question.length - 1) {
        this.currentIndex += 1;
      } else {
        clearTimeout(this.times);
        this.commitInfo();
        // if (this.userId) {
        //
        // } else {
        //   this.showDig();
        // }
      }
    }
  }
};
</script>
